import { ModalForm, ProFormText, ProFormSelect } from '@ant-design/pro-form';
import React, { useImperativeHandle, forwardRef, useState, useRef } from 'react';
import { message } from 'antd';
import request from '@/utils/request';
import apiPath from '@/utils/apiPath.js';
import md5 from 'js-md5';

const EditModalFormRef = (props, ref) => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState({});
  const modalformRef = useRef();
  
  useImperativeHandle(ref, () => ({
    initModal: (row) => {
      console.log(row);
      if (row.id) {
        row.roles = _.map(row.roles, v => v.id);
        modalformRef.current?.setFieldsValue(row);
      } else {
        modalformRef.current?.resetFields();
      }
      
      setCurrentRow(row);
      handleModalVisible(true);
    }
  }))

  /**
   * 添加节点
   *
   * @param fields
   */
  const handleAdd = async (fields) => {
    let method = 'POST';
    let url = apiPath.ADMIN_USER_HANDLE;
    if (currentRow.id) {
      method = 'PUT';
      url = `${url}/${currentRow.id}`;
    } else {
      // 密码输入验证
      if (fields.password !== fields.password2) {
        message.warning('密码输入不一致，请再次确认密码。1');
        return;
      }
      fields.password = md5(fields.password);
      fields = _.omit(fields, 'password2');
    }
    const hide = message.loading('正在添加');
    try {
      await request(url, {
        method,
        data: fields,
      });
      hide();
      message.success(`${currentRow.id ? '修改成功' : '添加成功'}`);
      props.onReload();
      return true;
    } catch (error) {
      console.error(error);
      hide();
      return false;
    }
  };

  return (
    <ModalForm
      title={`${currentRow.id ? '编辑' : '新建'}用户`}
      width="400px"
      formRef={modalformRef}
      layout="horizontal"
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 18 }}
      visible={createModalVisible}
      onVisibleChange={(value) => {
        handleModalVisible(value);
      }}
      onFinish={async (value) => {
        const success = await handleAdd(value);

        if (success) {
          handleModalVisible(false);

          if (actionRef.current) {
            actionRef.current.reload();
          }
        }
      }}
    >
      <ProFormText
        rules={[
          {
            required: true,
            message: "姓名为必填项",
          },
        ]}
        width="md"
        label="姓名"
        name="name"
      />
      <ProFormText
        rules={[
          {
            required: true,
            message: "手机号为必填项",
          },
        ]}
        width="md"
        label="手机号"
        name="phone"
      />
      {
        !currentRow.id &&
        <>
          <ProFormText.Password
            rules={[
              {
                required: true,
                message: "密码为必填项",
              },
              {
                type: 'pattern', 
                pattern: /^[0-9a-zA-Z]{6,12}$/,  
                message: '支持6-12位的数字和英文字母组合'
              }
            ]}
            width="md"
            label="密码"
            name="password"
            fieldProps={{
              autoComplete: "new-password"
            }}
          />
          <ProFormText.Password
            rules={[
              {
                required: true,
                message: "请再次确认密码",
              },
            ]}
            width="md"
            label="确认密码"
            name="password2"
          />
        </>
      }
      <ProFormSelect
        rules={[
          {
            required: true,
            message: "请选择用户状态",
          },
        ]}
        initialValue={1}
        options={[
            { label: '启用', value: 1 },
            { label: '禁止', value: 0 },
        ]}
        width="md"
        label="用户状态"
        name="status"
      />
      <ProFormSelect
        rules={[
          {
            required: true,
            message: "请选择角色",
          },
        ]}
        request={async () => {
          const res = await request(apiPath.ADMIN_ROLE_HANDLE, {
            method: 'GET',
            params: {
              page: 1,
              per_page: 1000
            },
          })
          return res.data.list.map(v => {
            return {
              label: v.name, 
              value: v.id
            }
          })
        }}
        mode="multiple"
        width="md"
        label="角色"
        name="roles"
      />
    </ModalForm>
  )
}
const EditModalForm = forwardRef(EditModalFormRef);
export default EditModalForm;